<template>
  <section class="contract-list">
    <!-- 头部 -->
    <custom-filter
        from="contractList"
        :haveImport="true"
        @search="handleSearch"
        :type="1"
        @importSuccess="getTableData"
        :initSearch="true"
    />
    <!-- 表格 -->
    <a-table
        :dataSource="dataList"
        :columns="columnsData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        sticky
        rowKey="id"
        :scroll="{ x: 'max-content'}"
        class="mt-10"
        :customRow="customRow"
    >
      <template #title>
        <a-row
            type="flex"
            justify="space-between"
            align="middle"
            class="table-header"
        >
          <a-col>
            <a-space :size="30">
              <span>合同列表</span>
              <a-tag :visible="tagVisible" closable @close="tagClose">
                <span style="padding-right: 5px"
                >🌱 提示：Shift+滚轮 可以控制表格横向滚动</span
                >
              </a-tag>
            </a-space>
          </a-col>
          <a-col>
            <a-space>
              <a-button class="mr-20" @click="downLoadClick" :loading="isExport"
              >
                <template #icon>
                  <DownloadOutlined/>
                </template>
                导出报表
              </a-button
              >
              <custom-columns
                  :colUrl="colUrl"
                  :type="typeList"
                  :newIcon="true"
                  :resetType="resetType"
                  from="contractList"
                  @getColumns="getColumns"
              />
            </a-space>
          </a-col>
        </a-row>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'owner_name'">
          <a @click.stop="ownerClick(record)">{{ text }}</a>
          <a-tag v-if="record.is_renewal == 1" color="green" class="ml-5"
          >已续
          </a-tag
          >
        </template>

        <template v-if="column.key === 'lease_endtime'">
          <span>{{ record.lease_endtime }}</span>
          <span v-if="record.timeout_status" style="color: #f9bd99">{{
              record.timeout_data
            }}</span>
          <span v-else style="color: red">{{ record.remind_data }}</span>
        </template>

        <template v-if="column.key === 'contract_tags'">
          <template v-if="text && text.length">
            <tag-list :list="text" :type="2"/>
          </template>
          <span v-else>--</span>
        </template>

        <template v-if="column.key === 'lease_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.lease_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'lease_deposit'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.lease_deposit_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'is_renewal'">
          <span>{{ text == 1 ? "是" : "否" }}</span>
        </template>

        <template v-if="column.key === 'property_deposit'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.property_deposit_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'property_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.property_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'lease_real_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.lease_real_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'property_real_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.property_real_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'status'">
          <a-tag :color="$store.getters.contractStatusColor[record.status_key]">
            {{ text }}
          </a-tag>
        </template>

        <template v-if="column.key === 'room_id'">
          <div v-if="record.build_bind && record.build_bind.room.length > 0">
            <RoomBuildBindInRecord :build_bind="record.build_bind"/>
          </div>
          <span v-else>--</span>
        </template>
      </template>
    </a-table>
    <!-- 租客详情 -->
    <OwnerDetailDrawer
        :visible="ownerDetailVisible"
        :id="ownerId"
        @cancel="ownerDetailVisible = false"
    />
  </section>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  onActivated,
  reactive,
  toRefs,
} from "vue";
import CustomFilter from "../../../components/contract/CustomFilter/contract.vue";
import {
  InsertRowAboveOutlined,
  DownloadOutlined,
  CloseOutlined,
} from "@ant-design/icons-vue";
import {Modal, notification, message} from "ant-design-vue";
import request from "../../../common/utils/request";
import TagList from "../../../components/Tag/show.vue";
import {useRouter, useRoute} from "vue-router";
import dict from "../../../common/utils/dict";
import utils from "../../../common/utils/utils";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import CustomColumns from "@/components/CustomColumns/index.vue";
import RoomBuildBindInRecord from "@/components/RoomBuildBindInRecord/index.vue";
const COL_RESET_TYPE = "autoContractListColumn";
import store from "../../../store";
import {xlsx} from "../../../common/utils/xlsx";

export default defineComponent({
  name: "contractList",
  components: {
    CustomColumns,
    CustomFilter,
    TagList,
    InsertRowAboveOutlined,
    DownloadOutlined,
    CloseOutlined,
    OwnerDetailDrawer,
    RoomBuildBindInRecord,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const sort = ref("");
    const order = ref("");
    const state = reactive({
      colUrl: {
        server: "/org",
        url: "/contract/getContractListColumn",
      },
      resetType: COL_RESET_TYPE,
      typeList: dict.CONTRACT_LIST_COL_SET,
      setUrl: {
        server: "/org",
        url: "/user/specialSetting",
      },
      isExport: false,
    });
    /**
     * @description:  table
     */
    const columns = ref([]);

    const customCols = [
      "owner_name",
      "lease_endtime",
      "contract_tags",
      "lease_unit_price",
      "lease_deposit",
      "is_renewal",
      "property_deposit",
      "property_unit_price",
      "lease_real_unit_price",
      "property_real_unit_price",
      "status",
      "room_id",
    ];
    const sorterCols = [
      "lease_starttime",
      "lease_endtime",
      "sign_time",
      "room_id",
      "retreat_time",
    ];

    const getColumns = (data) => {
      let arr = [];
      data.forEach((item) => {
        if (item.checked) {
          let col = {
            title: item.title,
            dataIndex: item.key,
            key: item.key,
            width: item.width || 150,
          };
          if (sorterCols.includes(item.key)) {
            col.sorter = true;
          }
          arr.push(col);
        }
      });

      columns.value = [...arr];
    };

    const columnsData = computed(() => {
      return columns.value.map((item) => {
        if (sorterCols.includes(item.key)) {
          item.sortOrder = order.value == item.key && sort.value ? sort.value == 'asc' ? 'ascend' : 'descend' : false;
        }
        return item
      })
    })

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };

    // 点击行
    const handleTableRowClick = (record) => {
      console.log("handleTableRowClick", record);
      // 去编辑
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_contractDetail_${record.id}`,
            app: 'org',
            name: `合同详情【${record.owner_name}】`,
            url: `/contract/contractDetail?id=${record.id}&noBack=1`,
          }
        })
      } else {
        $router.push({name: "contractDetail", query: {id: record.id}});
      }

    };

    const page = ref(1);
    const limit = ref(20);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
      showTotal: (total) => {
        return `共 ${total} 条`;
      },
    }));
    const loading = ref(false);
    const handleTableChange = (pager, filters, sorter) => {
      dataList.value = []
      sort.value = sorter.order == "ascend" ? "asc" : sorter.order == "descend" ? "desc" : undefined;
      if (sort.value) {
        order.value = sorter.field;
      } else {
        order.value = '';
      }
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableData();
    };

    const dataList = ref([]);
    const getTableData = () => {
      if (state.isExport) {
        loading.value = false;
      } else {
        loading.value = true;
      }
      return new Promise((resolve) => {
        request
            .post("/org", "/contract/contractList", {
              page: state.isExport ? 1 : page.value,
              limit: state.isExport ? 100000 : limit.value,
              sort: sort.value,
              order: order.value,
              ...searchValue.value,
            })
            .then((res) => {
              if (!state.isExport) {
                dataList.value = res.list;
                total.value = res.total;
                return;
              }
              resolve(res.list);
            })
            .finally(() => {
              loading.value = false;
            });
      });
    };

    const searchValue = ref({});
    const handleSearch = (params) => {
      searchValue.value = params;
      getTableData();
    };

    // 导出报表

    const downLoadClick = () => {
      let listHanders = {};
      listHanders = columns.value.reduce((obj, v) => {
        obj[v.key] = v.title;
        return obj;
      }, {});
      state.isExport = true;
      getTableData().then((res) => {
        let list = utils.deepClone(res);
        xlsx(list, listHanders, "合同列表");
        message.success("导出成功,请等待文件生成");
        state.isExport = false;
      });
    };

    const tagVisible = ref(false);
    onActivated(() => {
      if (
          !Boolean(utils.getStorage("tableShiftTipCache_contractList", false))
      ) {
        tagVisible.value = true;
      }
    });

    // 标签关闭
    const tagClose = () => {
      tagVisible.value = false;
      utils.setStorage("tableShiftTipCache_contractList", true, false);
    };

    // 租客详情
    const ownerDetailVisible = ref(false);
    const ownerId = ref(0);
    const ownerClick = (record) => {
      ownerId.value = record.owner_id;
      if (window.__MICRO_APP_ENVIRONMENT__) {
        ownerDetailVisible.value = true;
      } else {
        $router.push({ name: "ownerDetail", query: { id: record.owner_id } });
      }
    };

    watch(
        () => store.getters.contractListUpdate,
        (val) => {
          if (val) {
            console.log("刷新合同列表");
            store.dispatch("SetContractListUpdate", false).then(() => {
              getTableData();
            });
          }
        }
    );

    watch(
        () => store.getters.contractListInit,
        (val) => {
          if (val) {
            console.log("初始化合同列表");
            store.dispatch("SetContractListInit", false).then(() => {
              page.value = 1;
              getTableData();
            });
          }
        }
    );

    if ($route?.query?.order) {
      sort.value = $route?.query?.sort;
      order.value = $route?.query?.order;
    }

    return {
      ...toRefs(state),
      columns,
      columnsData,
      dataList,
      pagination,
      loading,
      handleTableChange,
      handleSearch,
      customRow,
      downLoadClick,
      tagClose,
      tagVisible,
      ownerClick,
      ownerId,
      ownerDetailVisible,
      getColumns,
      getTableData,
      total,
    };
  },
});
</script>

<style lang="less" scoped>
.contract-list {
  padding: 10px;

  .table-header {
    margin: 0 20px;
    color: rgba(0, 0, 0, 0.8);
  }
}

:deep(.ant-pagination-total-text) {
  margin-right: 20px;
}
</style>
